package webapi

import (
	"ims/app/dao"
	"ims/app/ws"
	"time"

	"ims/tools/response"

	"github.com/gogf/gf/container/garray"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/util/gconv"
)

var User = userApi{}

type userApi struct{}

func (c *userApi) GetRecordList(r *ghttp.Request) {
	idTo := r.GetString("idTo", 0)
	limit := r.GetString("limit", 0)
	toUserId := r.GetString("toUserId", 0)
	cookieUid := r.GetString("cookieUid", 0)
	kefuUd := r.GetString("kefu_id", 0)
	kefuRand := r.GetString("kefu_rand", 0)

	user := make(map[string]string)
	user["appid"] = ws.APPID
	user["uid"] = r.GetString("uid", "")
	user["nickname"] = r.GetString("nickname", "")
	user["phone"] = r.GetString("phone", "")
	user["sex"] = r.GetString("sex", "")
	user["avatar"] = r.GetString("avatar", "")
	user["openid"] = r.GetString("openid", "")
	user["type"] = r.GetString("type", "")
	user["lastIp"] = r.GetClientIp()

	ret, err := c.GetRecord(user, idTo, limit, toUserId, cookieUid, kefuUd, kefuRand)
	if err != nil {
		//当前没有客服在线
		response.JsonResponse(r, g.Map{
			"status": 400,
			"msg":    "fail",
			"data":   err.Error(),
		})
	}
	response.JsonResponse(r, g.Map{
		"status": 200,
		"msg":    "ok",
		"data":   ret,
	})
}

func (*userApi) GetRecord(user map[string]string, idTo string, limit string,
	toUserId string, cookieUid string, kefuId string, kefuRand string) (map[string]interface{}, error) {

	uid := 0
	if user["uid"] != "" {
		uid = gconv.Int(user["uid"])
	}

	userInfo := dao.GetChatUserInfo(uid)
	g.Log().Debug(userInfo)
	if uid == 0 || userInfo.Id == 0 {
		userInfo = dao.CreateChatUser(user)
	} else {
		var upinfo = make(map[string]string)
		if user["nickname"] != "" && user["nickname"] != userInfo.Nickname {
			upinfo["nickname"] = user["nickname"]
		}

		if user["avatar"] != "" && user["avatar"] != userInfo.Avatar {
			upinfo["avatar"] = user["avatar"]
		}

		dao.UpdateChatUser(upinfo, uid)
		userInfo = dao.GetChatUserInfo(uid)
	}
	// 获取指定user_id 或者kefuId的 客服
	toUserInfo := dao.GetChatServiceByIdOrUserId(kefuId, toUserId)
	if toUserInfo.Id == 0 {
		// 没有者获取 默认第一个客服
		toUserInfo = dao.GetChatService()

	}
	if toUserInfo.Id == 0 {
		return map[string]interface{}{}, gerror.New("客服不在线")
	}
	//合并输出数据
	ret := map[string]interface{}{
		"avatar":           userInfo.Avatar,
		"is_tourist":       userInfo.IsTourist,
		"nickname":         userInfo.Nickname,
		"serviceList":      garray.NewArray(true),
		"site_name":        "多米客服",
		"to_user_avatar":   toUserInfo.Avatar,
		"to_user_id":       toUserInfo.UserId,
		"to_user_nickname": toUserInfo.Nickname,
		"uid":              userInfo.Uid,
		"user_id":          userInfo.Id,
	}
	//获取历史聊天记录
	record := dao.GetChatDialogueRecordList(ws.APPID, userInfo.Id, gconv.Int(limit), gconv.Int(idTo))

	if len(record) > 0 {
		ret["serviceList"] = record
	}

	return ret, nil
}

//统计 访客聊天界面里面调用
// route: /api/mobile/user/statistics
func (*userApi) Statistics(r *ghttp.Request) {
	data := map[string]interface{}{}

	data["ip"] = r.GetString("ip", "127.0.0.1")
	data["browser"] = r.GetString("browser", "")
	data["path"] = r.GetString("path", "")
	data["source"] = r.GetString("source", "")

	dao.ChatStatistics.SaveSite(data)

	response.JsonResponse(r, g.Map{
		"status": 200,
		"msg":    "ok",
		"data":   "",
	})
}

//访客端 上传图片
// /api/mobile/service/upload
func (*userApi) Upload(r *ghttp.Request) {
	fieldName := r.GetString("filename")
	file := r.GetUploadFile(fieldName)

	cachekey := "start_uploads_" + r.GetString("appId") //appId 从中间件中解析header的token得到
	v, _ := gcache.GetOrSet(cachekey, 0, 60*time.Second)
	// 限制每分钟只能上传5张
	if gconv.Int(v) > 5 {
		response.JsonResponse(r, g.Map{
			"status": 404,
			"msg":    "上传图片太频繁了",
			"data":   g.Map{"name": "", "url": ""},
		})
	}

	name, err := file.Save("public/upload")
	//记录上传的次数 每小时
	blimit := gconv.Int(v) + 1
	gcache.Update(cachekey, blimit)

	//g.Log().Debug("0000000000000000======", blimit)
	// 获取站点域名信息
	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}
	host := scheme + "://" + r.Host

	if err != nil {
		response.JsonResponse(r, g.Map{
			"status": 404,
			"msg":    "fail",
			"data":   g.Map{"name": "", "url": ""},
		})
	} else {
		response.JsonResponse(r, g.Map{
			"status": 200,
			"msg":    "ok",
			"data":   g.Map{"name": name, "url": host + "/upload/" + name},
		})
	}
}
